<?php
class Model_TableCommune implements Model_ITable
{
	private static $con = null;
	private static $reqSelectAll = null;
        private static $reqSelectAllLimit = null;
	private static $reqSelectOne = null;
	private static $reqInsert = null;
	private static $reqDeleteOne = null;
	private static $reqUpdate = null;
        private static $reqCount = null;
	
	public static function setConnexion(MyPdo $pdo)
	{
		self::$con = $pdo;
	}
	
	public static function getConnexion()
	{
		return self::$con;
	}

	public static function init()
	{
		self::$reqSelectAll = self::$con->prepare('SELECT * FROM commune ORDER BY id_commune');
		self::$reqSelectOne = self::$con->prepare('SELECT * FROM commune WHERE id_commune = :idcond');
		self::$reqDeleteOne = self::$con->prepare('DELETE FROM commune WHERE id_commune = :idcond');
		self::$reqInsert = self::$con->prepare('INSERT INTO commune(nom, code_postal) VALUES(:nom, :codepostal)');
		self::$reqUpdate = self::$con->prepare('UPDATE commune SET nom = :nom, code_postal = :codepostal WHERE id_commune = :idcond');
                self::$reqCount = self::$con->prepare('SELECT COUNT(*) FROM commune');
                self::$reqSelectAllLimit = self::$con->prepare('SELECT * FROM commune ORDER BY id_commune LIMIT :begin, :nb');
	}

	public static function fetchAll()
	{
		self::$reqSelectAll->execute();
		$results = self::$reqSelectAll->fetchAll();
		return $results;
	}

        public static function fetchAllLimit($begin, $nb)
        {
            self::$reqSelectAllLimit->bindParam(':begin', $begin, PDO::PARAM_INT);
            self::$reqSelectAllLimit->bindParam(':nb', $nb, PDO::PARAM_INT);
            self::$reqSelectAllLimit->execute();
            return self::$reqSelectAllLimit->fetchAll();
        }

	public static function fetchOne($id)
	{
		self::$reqSelectOne->execute(array('idcond' => $id));
		$results = self::$reqSelectOne->fetchAll();
		if( empty($results[0]) )
			return array();
		else
			return $results[0];
	}
	
	public static function delete($id)
	{
		self::$reqDeleteOne->execute(array(':idcond' => $id));
	}
	
	public static function insert($nom, $codepostal)
	{
		self::$reqInsert->execute(array(':nom' => $nom, ':codepostal' => $codepostal));
		return self::$con->lastInsertId();
	}
	
	public static function update($id, $nom, $codepostal)
	{
		self::$reqUpdate->execute(array(':nom' => $nom, ':codepostal' => $codepostal, ':idcond' => $id));
	}

        public static function count()
        {
            self::$reqCount->execute();
            return self::$reqCount->fetchColumn();
        }
}
